package com.nti56.springboot.controller;



import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.nti56.springboot.model.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import com.nti56.springboot.cache.BaseDataCache;
import com.nti56.springboot.service.UserService;
import com.nti56.springboot.utils.Constant;
import com.nti56.springboot.utils.MD5Util;
import com.nti56.springboot.utils.TreeNodeUtil;



@RequestMapping("user")
@Controller
public class UserController  extends BaseController{
    
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
    private UserService userService;
	@Autowired
	private BaseDataCache baseDataCache;
	
	@RequestMapping("/toUserList")
	@RequiresPermissions("User:toUserList")
    public String toUserList(HttpServletRequest request, Model model){
		model.addAttribute("orgRootId", Constant.HBZY_ORGANIZATION_ROOT_ID);
        return "system/userList";
    }
	
	@RequestMapping("toUserAdd")
    public String toUserAdd(HttpServletRequest request, Model model){
		Map map = this.getParamMap(request);
		String userId = (String) request.getParameter("userId");
		if(StringUtil.isEmpty(userId)) {
			String orgId = (String)map.get("orgId");
			model.addAttribute("orgId", orgId);
		}else {
			User user = userService.getById(userId);
			model.addAttribute("userId", userId);
			model.addAttribute("user", user);
		}	
		model.addAttribute("roleType", Constant.SYS_ROLE_TYPE_OPERATE);
        return "system/userAdd";
    }
	
	@RequestMapping("/listUsers")
    @ResponseBody
    //@SystemControllerLog(description = "查询用户信息",actionType = "4")
    public PageResponse listUsers(HttpServletRequest request){
		PageResponse pg = new PageResponse();
		try {
			Map map = this.getParamMap(request);
			String orgId = (String)map.get("orgId");
			if(!StringUtil.isEmpty(orgId)) {
				List<String> orgIds = this.getSubOrgIds(orgId);
				map.remove("orgId");
				map.put("orgIds", orgIds);;
			}
	    	this.startPage(request);
	        List<User> list = userService.getUserList(map);
	        pg = this.getPageResponse(list);
		}catch(Exception e) {
			pg = this.getErrorPageResponse(e);
			throw e;
		}
    	return pg;
    }
	
	/**
	 * 根据父ID，获取所有子ID， （含父ID）
	 * @param pId
	 * @return
	 */
	private List<String> getSubOrgIds(String pId){
		List<Organization> orgList = this.baseDataCache.getOrganizations();
		List<TreeNode> nodeList = Organization.orgList2SimpleNodeList(orgList);
		List<TreeNode> children = new ArrayList<TreeNode>();
		TreeNodeUtil.getSimpleChilds(children,nodeList,pId);
		List<String> orgIds = new ArrayList<String>();
		orgIds.add(pId);
		for(TreeNode tn : children) {
			orgIds.add(tn.getId());
		}
		return orgIds;
	}
	
	@RequestMapping("/addUser")
    @ResponseBody
    public AjaxResult addUser(HttpServletRequest request){
    	try {
    		Map map = this.getParamMap(request);
    		String userId = (String)map.get("userId");
    		String userName = (String)map.get("userName");
    		String realName = (String)map.get("realName");
    		String passWord = (String)map.get("passWord");
    		String orgId = (String)map.get("orgId");
    		String entities = (String)map.get("entities");
    		List<DataList> results = JSON.parseArray("["+entities+"]", DataList.class);
    		List<Role> roleList = this.dataList2Role(results);
    		User user = new User();
    		user.setUserId(userId);
    		user.setUserName(userName);
    		user.setRealName(realName);
    		user.setOrgId(orgId);    		
    		if(StringUtil.isEmpty(userId)) {
    			user.setPassWord(MD5Util.MD5(passWord));
    			userService.savaUser(user, roleList);
    			return new AjaxResult(true,AjaxResult.SAVE_OK);
    		}else {
    			userService.updateUser(user,Constant.SYS_ROLE_TYPE_OPERATE,roleList);
    			return new AjaxResult(true,AjaxResult.UPDATE_OK);
    		}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return new AjaxResult(false,e.getMessage(),AjaxResult.SAVE_FAIL);
		}
    }
	
	@RequestMapping("/updUserDataAuth")
    @ResponseBody
    public AjaxResult updUserDataAuth(HttpServletRequest request){
    	try {
    		Map map = this.getParamMap(request);
    		String userId = (String)map.get("userId");    		
    		String entities = (String)map.get("entities");
    		User user = this.userService.getById(userId);
    		if(StringUtil.isEmpty(entities)) {
    			//清除数据角色
    			userService.updateUser(user,Constant.SYS_ROLE_TYPE_DATA_AUTH, null);
    		}else {
    			List<DataList> results = JSON.parseArray("["+entities+"]", DataList.class);
        		List<Role> roleList = this.dataList2Role(results);
        		userService.updateUser(user,Constant.SYS_ROLE_TYPE_DATA_AUTH, roleList);
    		}
    		return new AjaxResult(true,AjaxResult.UPDATE_OK);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return new AjaxResult(false,e.getMessage(),AjaxResult.SAVE_FAIL);
		}
    }
	
	
	private List<Role> dataList2Role(List<DataList> list){
		Role r = null;
		List<Role> roleList = new ArrayList<Role>();
		for(DataList d : list){
			r = new Role();
			r.setRoleId(d.getValue());
			r.setRoleName(d.getText());
			roleList.add(r);
		}
		return roleList;
	}
	
	@RequestMapping("/deleteUser")
    @ResponseBody
    public AjaxResult deleteUser(HttpServletRequest request){
    	try {
    		Map map = this.getParamMap(request);
        	String ids = (String) map.get("ids");
    		List<String> list = Arrays.asList(ids.split(","));
    		for(String userId : list){
    			userService.deleteUser(userId);
    		}
			return new AjaxResult(true,AjaxResult.DLELETE_OK);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return new AjaxResult(false,e.getMessage(),AjaxResult.DLELETE_FAIL);
		}
    }
	
	
	@RequestMapping("toRestSelfPwd")
	public String toRestSelfPwd(HttpServletRequest request, Model model){
		return "system/restSelfPwd";
	}
	
	@RequestMapping("toRestUserPwd")
	public String toRestUserPwd(HttpServletRequest request, Model model){
		String userId = (String) request.getParameter("userId");		
		User user = userService.getById(userId);
		model.addAttribute("userId", userId);
		model.addAttribute("user", user);
		return "system/restUserPwd";
	}
	
	/**
	   * 修改自身密码
	 * @param request
	 * @return
	 */
	@RequestMapping("/restSelfPwd")
    @ResponseBody
    public AjaxResult restSelfPwd(HttpServletRequest request){
    	try {
    		Map map = this.getParamMap(request);
    		User user = this.getLoginUser();
    		map.put("userId", user.getUserId());
    		this.userService.restSelfPwd(map);
			return new AjaxResult(true,AjaxResult.UPDATE_OK);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return new AjaxResult(false,e.getMessage(),AjaxResult.DLELETE_FAIL);
		}
    }
	
	/**
	   * 修改用户密码
	 * @param request
	 * @return
	 */
	@RequestMapping("/restUserPwd")
    @ResponseBody
    public AjaxResult restUserPwd(HttpServletRequest request){
    	try {
    		Map map = this.getParamMap(request);
    		String userId = (String) map.get("userId");
    		map.put("userId", userId);
    		this.userService.restUserPwd(map);
			return new AjaxResult(true,AjaxResult.UPDATE_OK);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			return new AjaxResult(false,e.getMessage(),AjaxResult.DLELETE_FAIL);
		}
    }
	
	
	@RequestMapping("toDataAuthUpd")
	public String toDataAuthUpd(HttpServletRequest request, Model model){
		String userId = (String) request.getParameter("userId");		
		User user = userService.getById(userId);
		model.addAttribute("userId", userId);
		model.addAttribute("user", user);
		model.addAttribute("roleType", Constant.SYS_ROLE_TYPE_DATA_AUTH);
		return "system/dataAuthUpd";
	}
	
	@RequestMapping("/getUserById")
    @ResponseBody
    public User getUserById(String userId){
		User user = userService.getById(userId);
		return user;
    }
	
	/**
	 * 根据用户userId 查询角色
	 * @param request
	 * @return
	 */
	@RequestMapping("/getCurrentRoles")
    @ResponseBody
    public List<DataList> getCurrentRoles(HttpServletRequest request){ 
		String userId = (String) request.getParameter("userId");
		String roleType = (String) request.getParameter("roleType");
        List<Role> list = userService.getRoleListByUserId(userId,roleType);
        List<DataList> dataLists = new ArrayList<DataList>();
        DataList dl = null;
        for(Role r : list){
        	dl = new DataList();
        	dl.setValue(r.getRoleId());
        	dl.setText(r.getRoleName());
        	dataLists.add(dl);
        }
        return dataLists;
    }
}